<template>
  <div class="chat-container h-screen bg-gray-50 flex">
    <!-- 侧边栏 -->
    <div class="sidebar w-80 bg-white border-r border-gray-200 flex flex-col shadow-sm">
      <!-- 侧边栏头部 -->
      <div class="sidebar-header p-6 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">对话列表</h3>
        <button
          @click="createNewConversation"
          class="btn-primary w-full flex items-center justify-center"
        >
          <Icon name="plus" size="18" class="mr-2" />
          新建对话
        </button>

        <!-- 手动刷新按钮 -->
        <button
          @click="refreshConversationList"
          :disabled="isUpdatingTitle"
          class="mt-2 w-full flex items-center justify-center px-3 py-2 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Icon
            name="refresh-cw"
            size="16"
            class="mr-2"
            :class="{ 'animate-spin': isUpdatingTitle }"
          />
          {{ isUpdatingTitle ? '刷新中...' : '刷新列表' }}
        </button>

        <!-- 标题更新状态指示器 -->
        <div
          v-if="isUpdatingTitle"
          class="mt-3 flex items-center justify-center text-sm text-blue-600"
        >
          <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
          正在更新对话标题...
        </div>
      </div>

      <!-- 对话列表 -->
      <div class="conversation-list flex-1 overflow-y-auto">
        <div
          v-for="conversation in conversations"
          :key="`${conversation.id}-${conversation.title}`"
          class="conversation-item p-4 border-b border-gray-100 cursor-pointer transition-all duration-200 hover:bg-gray-50 group"
          :class="{
            'bg-blue-50 border-l-4 border-l-blue-500':
              currentConversation && currentConversation.id === conversation.id,
          }"
          @click="selectConversation(conversation.id)"
        >
          <div class="conversation-title font-medium text-gray-900 mb-1 truncate">
            {{ conversation.title || '新对话' }}
          </div>
          <div class="conversation-time text-xs text-gray-500 mb-2">
            {{ formatTime(conversation.updateTime) }}
          </div>
          <div class="conversation-actions opacity-0 group-hover:opacity-100 transition-opacity">
            <button
              @click.stop="deleteConversation(conversation.id)"
              class="btn-text text-red-600 hover:text-red-700 text-xs p-1"
            >
              <Icon name="trash" size="14" />
            </button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="conversations.length === 0" class="p-8 text-center text-gray-500">
          <Icon name="message-circle" size="48" class="mx-auto mb-4 text-gray-300" />
          <p>暂无对话记录</p>
          <p class="text-sm">点击上方按钮开始新对话</p>
        </div>
      </div>

      <!-- 侧边栏底部 -->
      <div class="sidebar-footer p-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <div
              class="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center mr-3"
            >
              <Icon name="user" size="16" class="text-white" />
            </div>
            <span class="text-sm font-medium text-gray-900">
              {{ user && (user.nickname || user.username) }}
            </span>
          </div>
          <button @click="logout" class="btn-text text-gray-600 hover:text-gray-900 text-sm">
            退出
          </button>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main flex-1 flex flex-col">
      <!-- 欢迎界面 -->
      <div
        v-if="!currentConversation"
        class="welcome-screen flex-1 flex items-center justify-center"
      >
        <div class="text-center">
          <div
            class="w-24 h-24 bg-gradient-to-br from-blue-500 to-purple-600 rounded-3xl flex items-center justify-center mx-auto mb-6 shadow-lg"
          >
            <Icon name="robot" size="48" class="text-white" />
          </div>
          <h1 class="text-3xl font-bold text-gray-900 mb-4">欢迎使用AI对话助手</h1>
          <p class="text-lg text-gray-600 mb-8">选择一个对话开始聊天，或者创建新的对话</p>
          <button @click="createNewConversation" class="btn-primary px-8 py-3 text-lg">
            <Icon name="plus" size="20" class="mr-2" />
            开始新对话
          </button>
        </div>
      </div>

      <!-- 聊天内容 -->
      <div v-else class="chat-content flex-1 flex flex-col">
        <!-- 消息列表 -->
        <div class="message-list h-[calc(100vh-200px)] overflow-y-auto p-4" ref="messageListRef">
          <MessageBubble
            v-for="message in messages"
            :key="message.id"
            :message="message"
            :enable-typewriter="enableTypewriter"
            @regenerate="regenerateMessage"
          />

          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator flex items-center p-4">
            <div class="typing-dots flex gap-1 mr-3">
              <span class="w-2 h-2 bg-blue-500 rounded-full animate-bounce"></span>
              <span
                class="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                style="animation-delay: 0.1s"
              ></span>
              <span
                class="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                style="animation-delay: 0.2s"
              ></span>
            </div>
            <span class="text-gray-500 text-sm">AI正在思考...</span>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area border-t border-gray-200 bg-white p-6">
          <div class="max-w-4xl mx-auto">
            <div
              class="input-container bg-gray-50 rounded-2xl border border-gray-200 focus-within:border-blue-500 focus-within:ring-2 focus-within:ring-blue-200 transition-all duration-200 flex items-center justify-between"
            >
              <textarea
                ref="messageInputRef"
                v-model="messageInput"
                :rows="3"
                placeholder="请输入您的消息..."
                class="w-full px-4 py-3 bg-transparent border-none rounded-2xl outline-none resize-none text-gray-900 placeholder-gray-500 input-textarea"
                @keydown.enter.exact="sendMessage"
                @keydown.ctrl.enter="addNewLine"
                :disabled="isTyping"
              ></textarea>

              <div class="flex items-center w-[100px] pl-3">
                <button
                  @click="sendMessage"
                  :disabled="!messageInput.trim() || isTyping"
                  class="btn-primary p-2 flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Icon name="send" size="16" class="mr-1" />
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Icon from '../components/icons/Icon.vue'
import MessageBubble from '../components/MessageBubble.vue'
import api from '../utils/api'

export default {
  name: 'Chat',
  components: {
    Icon,
    MessageBubble,
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    const messageListRef = ref()
    const messageInputRef = ref()
    const messageInput = ref('')
    const isTyping = ref(false)
    const enableTypewriter = ref(true)
    const isUpdatingTitle = ref(false) // 标题更新状态

    const user = computed(() => store.state.user)
    const conversations = computed(() => store.state.conversations)
    const currentConversation = computed(() => store.state.currentConversation)
    const messages = computed(() => store.state.messages)

    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now.getTime() - date.getTime()

      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
      if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
      return date.toLocaleDateString('zh-CN')
    }

    const scrollToBottom = () => {
      nextTick(() => {
        if (messageListRef.value) {
          messageListRef.value.scrollTop = messageListRef.value.scrollHeight
        }
      })
    }

    // 刷新对话列表，确保标题同步
    const refreshConversationList = async () => {
      if (isUpdatingTitle.value) {
        console.log('标题更新中，跳过重复刷新')
        return
      }

      isUpdatingTitle.value = true
      try {
        await store.dispatch('fetchConversations')
        console.log('对话列表已刷新')

        // 显示成功提示（可选）
        // showSuccessMessage('对话标题已更新')
      } catch (error) {
        console.warn('刷新对话列表失败:', error)
        // 如果刷新失败，尝试延迟重试
        setTimeout(async () => {
          try {
            await store.dispatch('fetchConversations')
            console.log('对话列表重试刷新成功')
          } catch (retryError) {
            console.error('对话列表重试刷新失败:', retryError)
            showErrorMessage('对话标题更新失败，请手动刷新')
          }
        }, 1000)
      } finally {
        isUpdatingTitle.value = false
      }
    }

    // 更新当前对话的标题（本地更新，不调用API）
    const updateCurrentConversationTitle = (newTitle) => {
      if (currentConversation.value) {
        store.dispatch('updateConversationTitleLocal', {
          conversationId: currentConversation.value.id,
          title: newTitle,
        })
        console.log('当前对话标题已本地更新:', newTitle)
      }
    }

    const createNewConversation = async () => {
      try {
        const response = await store.dispatch('createConversation', '新对话')
        await store.dispatch('fetchConversations')

        // 自动选择新创建的对话
        if (response && response.data) {
          await store.dispatch('fetchConversationMessages', response.data.id)
          scrollToBottom()
        }

        showSuccessMessage('创建新对话成功')
      } catch (error) {
        showErrorMessage('创建对话失败')
      }
    }

    const selectConversation = async (conversationId) => {
      try {
        await store.dispatch('fetchConversationMessages', conversationId)
        scrollToBottom()
      } catch (error) {
        showErrorMessage('加载对话失败')
      }
    }

    const deleteConversation = async (conversationId) => {
      try {
        if (!confirm('确定要删除这个对话吗？')) return

        await api.delete(`/chat/conversations/${conversationId}`)
        await store.dispatch('fetchConversations')

        if (currentConversation.value?.id === conversationId) {
          store.commit('SET_CURRENT_CONVERSATION', null)
          store.commit('SET_MESSAGES', [])
        }

        showSuccessMessage('删除成功')
      } catch (error) {
        showErrorMessage('删除失败')
      }
    }

    const sendMessage = async () => {
      if (!messageInput.value.trim() || !currentConversation.value) return

      const content = messageInput.value.trim()
      messageInput.value = ''
      isTyping.value = true

      try {
        if (enableTypewriter.value) {
          await sendMessageWithStream(content)
        } else {
          await sendMessageNormal(content)
        }
      } catch (error) {
        showErrorMessage('发送消息失败')
      } finally {
        isTyping.value = false
        scrollToBottom()
        // 消息发送完成后，自动聚焦到输入框
        await nextTick()
        if (messageInputRef.value) {
          messageInputRef.value.focus()
        }
      }
    }

    const sendMessageNormal = async (content) => {
      await store.dispatch('sendMessage', {
        conversationId: currentConversation.value.id,
        content,
      })

      // 普通消息发送完成后，刷新对话列表以显示更新后的标题
      await refreshConversationList()
    }

    const sendMessageWithStream = async (content) => {
      console.log('开始流式对话:', content)

      // 添加用户消息
      const userMessage = {
        id: Date.now(),
        role: 'user',
        content: content,
        createTime: new Date().toISOString(),
      }
      store.commit('ADD_MESSAGE', userMessage)
      console.log('用户消息已添加:', userMessage)

      // 添加AI消息占位符
      const aiMessageId = Date.now() + 1
      let aiMessage = {
        id: aiMessageId,
        role: 'assistant',
        content: '',
        createTime: new Date().toISOString(),
      }

      store.commit('ADD_MESSAGE', aiMessage)
      console.log(
        'AI消息占位符已添加，ID:',
        aiMessageId,
        '当前消息数组长度:',
        messages.value.length
      )

      try {
        // 使用 fetch API 实现流式响应
        const response = await fetch(`http://localhost:8080/api/chat/stream`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${store.state.token}`,
          },
          body: JSON.stringify({
            conversationId: currentConversation.value.id,
            content,
            model: currentConversation.value.model || 'gpt',
          }),
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        console.log('流式响应开始，状态:', response.status)
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let fullResponse = ''

        while (true) {
          const { done, value } = await reader.read()

          if (done) {
            console.log('流式响应完成')
            break
          }

          const chunk = decoder.decode(value)
          //console.log('收到数据块:', chunk)

          if (chunk.startsWith('data:')) {
            try {
              const line = chunk.slice(5)
              if (!line.startsWith('{')) {
                continue
              }
              const data = JSON.parse(line) // 移除 'data: ' 前缀

              if (data.content) {
                fullResponse += data.content

                // 使用消息ID更新AI消息内容
                store.commit('UPDATE_MESSAGE_BY_ID', {
                  messageId: aiMessageId,
                  content: fullResponse,
                })

                //console.log('AI消息已更新，ID:', aiMessageId, '当前内容:', fullResponse)

                // 强制触发 Vue 更新
                await nextTick()
              }

              if (data.finished) {
                console.log('流式响应完成标志')
                isTyping.value = false

                // 流式响应完成后，刷新对话列表以显示更新后的标题
                await refreshConversationList()

                // 流式响应完成后，自动聚焦到输入框
                await nextTick()
                if (messageInputRef.value) {
                  messageInputRef.value.focus()
                }
                return
              }
            } catch (e) {
              console.error('JSON解析错误:', e, '原始数据:', chunk)
            }
          }
        }

        isTyping.value = false
        console.log('流式对话完成，最终内容:', fullResponse)
        // 流式对话完成后，自动聚焦到输入框
        await nextTick()
        if (messageInputRef.value) {
          messageInputRef.value.focus()
        }
      } catch (error) {
        console.error('Stream error:', error)
        isTyping.value = false
        showErrorMessage('流式响应连接失败: ' + error.message)

        // 如果流式响应失败，回退到普通响应
        try {
          console.log('尝试回退到普通响应')
          await sendMessageNormal(content)
          // 普通响应完成后，自动聚焦到输入框
          await nextTick()
          if (messageInputRef.value) {
            messageInputRef.value.focus()
          }
        } catch (fallbackError) {
          console.error('普通响应也失败了:', fallbackError)
          showErrorMessage('普通响应也失败了: ' + fallbackError.message)
          // 即使失败也要聚焦到输入框
          await nextTick()
          if (messageInputRef.value) {
            messageInputRef.value.focus()
          }
        }
      }
    }

    const addNewLine = () => {
      messageInput.value += '\n'
    }

    const toggleTypewriter = () => {
      enableTypewriter.value = !enableTypewriter.value
    }

    const regenerateMessage = (message) => {
      // 重新生成消息的逻辑
      showInfoMessage('重新生成功能开发中...')
    }

    const logout = () => {
      store.dispatch('logout')
      router.push('/login')
    }

    const showSuccessMessage = (message) => {
      if (window.$toast) {
        window.$toast.success(message)
      }
    }

    const showErrorMessage = (message) => {
      if (window.$toast) {
        window.$toast.error(message)
      }
    }

    const showInfoMessage = (message) => {
      if (window.$toast) {
        window.$toast.info(message)
      }
    }

    // 监听消息变化，自动滚动到底部
    watch(
      messages,
      () => {
        scrollToBottom()
      },
      { deep: true }
    )

    onMounted(async () => {
      try {
        await store.dispatch('fetchConversations')
      } catch (error) {
        showErrorMessage('加载对话列表失败')
      }
    })

    return {
      messageListRef,
      messageInputRef,
      messageInput,
      isTyping,
      enableTypewriter,
      user,
      conversations,
      currentConversation,
      messages,
      formatTime,
      createNewConversation,
      selectConversation,
      deleteConversation,
      sendMessage,
      addNewLine,
      toggleTypewriter,
      regenerateMessage,
      logout,
      isUpdatingTitle,
    }
  },
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
}

.sidebar {
  width: 20rem;
}

.conversation-item {
  position: relative;
}

.conversation-item:hover .conversation-actions {
  opacity: 1;
}

.conversation-actions {
  position: absolute;
  top: 1rem;
  right: 1rem;
  opacity: 0;
  transition: opacity 0.2s;
}

.typing-indicator {
  padding: 1rem;
  margin-bottom: 1rem;
}

.typing-dots span {
  animation: bounce 1.4s infinite;
}

@keyframes bounce {
  0%,
  60%,
  100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 100%;
    position: absolute;
    z-index: 10;
    height: 100%;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.open {
    transform: translateX(0);
  }

  .chat-main {
    width: 100%;
  }
}

/* 消息列表滚动条样式 */
.message-list {
  scrollbar-width: thin;
  scrollbar-color: #cbd5e0 #f7fafc;
}

.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: #f7fafc;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a0aec0;
}
</style>
